package com.bun.ipmon.service;

import static com.google.appengine.api.taskqueue.TaskOptions.Builder.withUrl;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.logging.Level;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import com.bun.ipmon.dao.ConfigDao;
import com.bun.ipmon.vo.Config;
import com.google.appengine.api.memcache.ErrorHandlers;
import com.google.appengine.api.memcache.MemcacheService;
import com.google.appengine.api.memcache.MemcacheServiceFactory;
import com.google.appengine.api.taskqueue.Queue;
import com.google.appengine.api.taskqueue.QueueFactory;


public class IpMonService {
	public boolean hasPhone(){
		
		String small16gray = "http://store.apple.com/hk-zh/buy-iphone/iphone6?cppart=UNLOCKED/WW&product=MG472ZP/A&step=accessories";
		String small16silver = "http://store.apple.com/hk-zh/buy-iphone/iphone6?cppart=UNLOCKED/WW&product=MG482ZP/A&step=accessories";
		String small16gold = "http://store.apple.com/hk-zh/buy-iphone/iphone6?cppart=UNLOCKED/WW&product=MG492ZP/A&step=accessories";
		String small64gray = "http://store.apple.com/hk-zh/buy-iphone/iphone6?cppart=UNLOCKED/WW&product=MG4F2ZP/A&step=accessories";
		String small64silver = "http://store.apple.com/hk-zh/buy-iphone/iphone6?cppart=UNLOCKED/WW&product=MG4H2ZP/A&step=accessories";
		String small64gold = "http://store.apple.com/hk-zh/buy-iphone/iphone6?cppart=UNLOCKED/WW&product=MG4J2ZP/A&step=accessories";
		String small128gray = "http://store.apple.com/hk-zh/buy-iphone/iphone6?cppart=UNLOCKED/WW&product=MG4A2ZP/A&step=accessories";
		String small128silver = "http://store.apple.com/hk-zh/buy-iphone/iphone6?cppart=UNLOCKED/WW&product=MG4C2ZP/A&step=accessories";
		String small128gold = "http://store.apple.com/hk-zh/buy-iphone/iphone6?cppart=UNLOCKED/WW&product=MG4E2ZP/A&step=accessories";
		
		String big16gray = "http://store.apple.com/hk-zh/buy-iphone/iphone6?cppart=UNLOCKED/WW&product=MGA82ZP/A&step=accessories";
		String big16silver = "http://store.apple.com/hk-zh/buy-iphone/iphone6?cppart=UNLOCKED/WW&product=MGA92ZP/A&step=accessories";
		String big16gold = "http://store.apple.com/hk-zh/buy-iphone/iphone6?cppart=UNLOCKED/WW&product=MGAA2ZP/A&step=accessories";
		String big64gray = "http://store.apple.com/hk-zh/buy-iphone/iphone6?cppart=UNLOCKED/WW&product=MGAH2ZP/A&step=accessories";
		String big64silver = "http://store.apple.com/hk-zh/buy-iphone/iphone6?cppart=UNLOCKED/WW&product=MGAJ2ZP/A&step=accessories";
		String big64gold = "http://store.apple.com/hk-zh/buy-iphone/iphone6?cppart=UNLOCKED/WW&product=MGAK2ZP/A&step=accessories";
		String big128gray = "http://store.apple.com/hk-zh/buy-iphone/iphone6?cppart=UNLOCKED/WW&product=MGAC2ZP/A&step=accessories";
		String big128silver = "http://store.apple.com/hk-zh/buy-iphone/iphone6?cppart=UNLOCKED/WW&product=MGAE2ZP/A&step=accessories";
		String big128gold = "http://store.apple.com/hk-zh/buy-iphone/iphone6?cppart=UNLOCKED/WW&product=MGAF2ZP/A&step=accessories";
				
		
		Config config = getConfig();
		String device = config.getDevice();
		
		int targetCount = 0;
		int mobileCount = 0;
				
		if(device.equals("0") || device.equals("1") ){
			targetCount = 9;
			mobileCount = 9;
		}
		else if (device.equals("2")){
			targetCount = 18;
			mobileCount = 18;
		}
		
		int count = 0;
		int count2 = 0;
		
		MemcacheService syncCache = MemcacheServiceFactory.getMemcacheService();
		syncCache.setErrorHandler(ErrorHandlers.getConsistentLogAndContinue(Level.INFO));

		try {
			HttpURLConnection connection = null;
			URL url = new URL("http://store.apple.com/hk-zh/buy-iphone/iphone6");
			
			connection = (HttpURLConnection) url.openConnection();
			
			connection.setRequestMethod("GET");
			connection.setRequestProperty("Content-Type", "text/plain; charset=utf-8");
			connection.setRequestProperty("Content-Length",	"" + Integer.toString("".getBytes().length));
			connection.setRequestProperty("Content-Language", "en-US");

			connection.setUseCaches(false);
			connection.setDoInput(true);
			connection.setDoOutput(true);

			// Send request
			DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
			wr.flush();
			wr.close();

			// Get Response
			InputStream is = connection.getInputStream();
			BufferedReader rd = new BufferedReader(new InputStreamReader(is, "utf-8"));
		    String line;
		    
		    boolean websiteDown = true;
    		String finalDetail = "";

		    
		    while ((line = rd.readLine()) != null) {
		    	if(line.trim().startsWith("window.productSelectionController.addData")){
		    		websiteDown = false;
		    		
		    		//System.out.println(line);
		    		String detail = line.substring(line.indexOf("{\"dimensionScreensize\":\"4_7inch\",\"dimensionColor\":\"space_gray\""), line.indexOf("\"actionUrl\"")-1);
		    		detail = detail.replace("\"width\":\"470\"}},{\"dimensionScreensize\"", "\"width\":\"470\"}}<br/>{\"dimensionScreensize\"");
		    		detail = detail.replace("\"height\":\"556\"}},{\"dimensionScreensize\"", "\"height\":\"556\"}}<br/>{\"dimensionScreensize\"");
		    		String[] array = detail.split("<br/>");
		    		for(int i=0; i<array.length; i++){
		    			String status = array[i].substring(array[i].indexOf("displayShippingQuote\":\"")+23,array[i].indexOf("isPromotionEnabled")-3);
		    			String model = array[i].substring(array[i].indexOf("part\":\"I")+7,array[i].indexOf("showShipLabel")-3);
		    			String gb = array[i].substring(array[i].indexOf("dimensionCapacity\":\"")+20,array[i].indexOf("partNumber")-3);
		    			String colour = array[i].substring(array[i].indexOf("dimensionColor")+17,array[i].indexOf("dimensionCapacity")-3);
		    			String href = "";
		    			
		    			if((device.equals("0") && model.equals("IPHONE6P")) || (device.equals("1") && model.equals("IPHONE6")) || device.equals("2") ){
		    				if(model.equals("IPHONE6")){
		    					if(gb.equals("16gb")){
		    						if(colour.equals("space_gray")){
		    							href = "<a href=\"" +small16gray+"\">";
		    						}
		    						else if(colour.equals("silver")){
		    							href = "<a href=\"" +small16silver+"\">";
		    						}
		    						else if(colour.equals("gold")){
		    							href = "<a href=\"" +small16gold+"\">";
		    						}
		    					}
		    					else if(gb.equals("64gb")){
		    						if(colour.equals("space_gray")){
		    							href = "<a href=\"" +small64gray+"\">";
		    						}
		    						else if(colour.equals("silver")){
		    							href = "<a href=\"" +small64silver+"\">";
		    						}
		    						else if(colour.equals("gold")){
		    							href = "<a href=\"" +small64gold+"\">";
		    						}
		    					}
		    					else if(gb.equals("128gb")){
		    						if(colour.equals("space_gray")){
		    							href = "<a href=\"" +small128gray+"\">";
		    						}
		    						else if(colour.equals("silver")){
		    							href = "<a href=\"" +small128silver+"\">";
		    						}
		    						else if(colour.equals("gold")){
		    							href = "<a href=\"" +small128gold+"\">";
		    						}
		    					}
		    				}
		    				else if (model.equals("IPHONE6P")){
		    					if(gb.equals("16gb")){
		    						if(colour.equals("space_gray")){
		    							href = "<a href=\"" +big16gray+"\">";
		    						}
		    						else if(colour.equals("silver")){
		    							href = "<a href=\"" +big16silver+"\">";
		    						}
		    						else if(colour.equals("gold")){
		    							href = "<a href=\"" +big16gold+"\">";
		    						}
		    					}
		    					else if(gb.equals("64gb")){
		    						if(colour.equals("space_gray")){
		    							href = "<a href=\"" +big64gray+"\">";
		    						}
		    						else if(colour.equals("silver")){
		    							href = "<a href=\"" +big64silver+"\">";
		    						}
		    						else if(colour.equals("gold")){
		    							href = "<a href=\"" +big64gold+"\">";
		    						}
		    					}
		    					else if(gb.equals("128gb")){
		    						if(colour.equals("space_gray")){
		    							href = "<a href=\"" +big128gray+"\">";
		    						}
		    						else if(colour.equals("silver")){
		    							href = "<a href=\"" +big128silver+"\">";
		    						}
		    						else if(colour.equals("gold")){
		    							href = "<a href=\"" +big128gold+"\">";
		    						}
		    					}
		    				}
		    				finalDetail += href+status + "</a> ";
		    				
		    				
		    				finalDetail += model + " ";
		    				finalDetail += gb + " ";
		    				finalDetail += colour + "<br/>\r\n";
		    			}
		    			
		    		}
		    		
		    		syncCache.put("detail", finalDetail);

		    		//System.out.println(finalDetail);
					break;
				}
		    }
		    rd.close();
		    
		    if(websiteDown){
		    	return false;
		    }

			Pattern p = Pattern.compile("暫無供應");
		    Matcher m = p.matcher(finalDetail);
		    while (m.find()){
		    	count +=1;
		    }

			Pattern p2 = Pattern.compile("暫時無法提供");
		    Matcher m2 = p2.matcher(finalDetail);
		    while (m2.find()){
		    	count +=1;
		    }
		    
		    
		    
			Pattern p3 = Pattern.compile("IPHONE6 ");
		    Matcher m3 = p3.matcher(finalDetail);
		    while (m3.find()){
		    	count2 +=1;
		    }

			Pattern p4 = Pattern.compile("IPHONE6P ");
		    Matcher m4 = p4.matcher(finalDetail);
		    while (m4.find()){
		    	count2 +=1;
		    }
		    
		    //System.out.println(count);
		} catch (Exception e) {
			syncCache.delete("detail");
			e.printStackTrace();
			return false;
		}
		
	    if(count != targetCount && count2 == mobileCount ){
	    	return true;
	    }
	    else {
	    	return false;
	    }
	}
	
	public String buy(){
		String output="";
		try {
			
			// put iphone to cart
			HttpURLConnection connection1 = null;
			URL url1 = new URL("http://store.apple.com/hk-zh/buy-iphone/iphone5s?ao.iphone5scasegrid_leather=none&ao.applecareplus=none&ao.iphone5sdock=none&ao.lightning_usb_cable=none&ao.add_5w_usb_power_adapter=none&ao.lightning_30pin_adapter=none&ao.lightning_30pin_02m=none&ao.lightning_av=none&ao.apple_tv=none&add-to-cart=add-to-cart&cppart=UNLOCKED%2FWW&product=MF353ZP%2FA&step=accessories&complete=true");
			connection1 = (HttpURLConnection) url1.openConnection();
			connection1.setRequestMethod("GET");
			connection1.setRequestProperty("Content-Type", "text/plain; charset=utf-8");
			connection1.setRequestProperty("Content-Length",	"" + Integer.toString("".getBytes().length));
			connection1.setRequestProperty("Content-Language", "en-US");
			connection1.setUseCaches(false);
			connection1.setDoInput(true);
			connection1.setDoOutput(true);
			System.out.println("Response code:"+connection1.getResponseCode());
			// Send request
			DataOutputStream wr1 = new DataOutputStream(connection1.getOutputStream());
			wr1.flush();
			wr1.close();
			// Get Response
			InputStream is1 = connection1.getInputStream();
			BufferedReader rd1 = new BufferedReader(new InputStreamReader(is1, "utf-8"));
		    String line1;
		    String nexturl1 = "http://store.apple.com";
		    while ((line1 = rd1.readLine()) != null) {
		    	if(line1.trim().startsWith("controller.content.set(")){
		    		nexturl1 += line1.substring(line1.indexOf("\"url\":\"/hk-zh/cartx")+7,line1.indexOf("\"}},\"_events\":[{\"id\":\"checkout-now\""));
		    		break;
		    	}
		    }
	    	//System.out.println(nexturl1);

	    	//System.out.println("=================================================================");
		    System.out.println("11111111111111111111111111111111111111111111111111111111111111111");
		    //System.out.println("=================================================================");
		    
		 // click checkout to go to signin page
 			HttpURLConnection connection2 = null;
 			//URL url2 = new URL("https://secure2.store.apple.com/hk-zh/sign_in?c=aHR0cDovL3N0b3JlLmFwcGxlLmNvbS9oay16aC9jYXJ0fDFhb3NjNTgxZWNjODBjNDQ2MWU5NThlNTBkNDA5ZDFhNWQzNzFkYmRkZTkx&o=O01GMzUz&r=SXYD4UDAPXU7P7KXF&s=aHR0cHM6Ly9zZWN1cmUyLnN0b3JlLmFwcGxlLmNvbS9oay16aC9jaGVja291dC9zdGFydD9wbHRuPTlDNjM0RjREfDFhb3NjMWIzYzE3ODVhYTc4ZmJmMzI2NzE4ZDVlNGNjOTIzNTA1YTAzY2U1&t=SXYD4UDAPXU7P7KXF&up=t");
 			URL url2 = new URL(nexturl1);
 			connection2 = (HttpURLConnection) url2.openConnection();
 			connection2.setRequestMethod("POST");
 			connection2.setRequestProperty("Content-Type", "text/plain; charset=utf-8");
 			connection2.setRequestProperty("Content-Length",	"" + Integer.toString("".getBytes().length));
 			connection2.setRequestProperty("Content-Language", "en-US");
 			connection2.setUseCaches(false);
 			connection2.setDoInput(true);
 			connection2.setDoOutput(true);
 			System.out.println("Response code:"+connection2.getResponseCode());
 			// Send request
 			DataOutputStream wr2 = new DataOutputStream(connection2.getOutputStream());
 			wr2.flush();
 			wr2.close();
 			
			
 			// Get Response
 			InputStream is2 = connection2.getInputStream();
 			BufferedReader rd2 = new BufferedReader(new InputStreamReader(is2, "utf-8"));
 		    String line2;
 		    String nexturl2 = "";
 		    String o = "";
 		    String c = "";
 		    String r = "";
 		    String s = "";
 		    String t = "";
 		    
 		    while ((line2 = rd2.readLine()) != null) {
 		    	System.out.println(line2);
 		    	nexturl2 = line2.substring(line2.indexOf("\"url\"")+7,line2.indexOf("\"}}}"));
 		    	c = line2.substring(line2.indexOf("?c=")+3,line2.indexOf("&o="));
 		    	o = line2.substring(line2.indexOf("&o=")+3,line2.indexOf("&r="));
 		    	r = line2.substring(line2.indexOf("&r=")+3,line2.indexOf("&s="));
 		    	s = line2.substring(line2.indexOf("&s=")+3,line2.indexOf("&t="));
 		    	t = line2.substring(line2.indexOf("&t=")+3,line2.indexOf("&up="));
 		    }
 		    //System.out.println(nexturl2);
 		   //System.out.println(c);
 		  //System.out.println(o);
 		  //System.out.println(r);
 		 //System.out.println(s);
		  //System.out.println(t);
 		    
	 
  		   //System.out.println("=================================================================");
 		   System.out.println("22222222222222222222222222222222222222222222222222222222222222222");
		   //System.out.println("=================================================================");
		    
 		   
		   // login with apple id
		   String urlParameter3 = URLEncoder.encode("login-appleId", "UTF-8")+"="+URLEncoder.encode("ccchungben@gmail.com", "UTF-8")+"&"+URLEncoder.encode("login-password", "UTF-8")+"=oyhoggnond3C";
		   String urlReferrer = "";
			HttpURLConnection connection3 = null;
			//URL url3 = new URL("https://secure2.store.apple.com/hk-zh/sign_in?c=aHR0cDovL3N0b3JlLmFwcGxlLmNvbS9oay16aC9jYXJ0fDFhb3NjNTgxZWNjODBjNDQ2MWU5NThlNTBkNDA5ZDFhNWQzNzFkYmRkZTkx&o=O01GMzUz&r=SXYD4UDAPXU7P7KXF&s=aHR0cHM6Ly9zZWN1cmUyLnN0b3JlLmFwcGxlLmNvbS9oay16aC9jaGVja291dC9zdGFydD9wbHRuPTlDNjM0RjREfDFhb3NjMWIzYzE3ODVhYTc4ZmJmMzI2NzE4ZDVlNGNjOTIzNTA1YTAzY2U1&t=SXYD4UDAPXU7P7KXF&up=t");
			//URL url3 = new URL("https://secure2.store.apple.com/hk-zh/sentryx/sign_in");
			urlReferrer = "https://secure2.store.apple.com/hk-zh/sign_in?c="+c+"&o="+o+"&r="+r+"&s="+s+"&t="+t+"&up=t";
			URL url3 = new URL("https://secure2.store.apple.com/hk-zh/sentryx/sign_in?login-appleId=ccchungben@gmail.com&login-password=oyhoggnond3C&_a=login.sign&c="+c+"&_fid=si&r="+r+"&s="+s+"&t="+t+"&up=t");
			connection3 = (HttpURLConnection) url3.openConnection();
			
			connection3.setRequestMethod("GET");
			connection3.setRequestProperty("Content-Type", "text/plain; charset=utf-8");
			connection3.setRequestProperty("Content-Length",	"" + Integer.toString(urlParameter3.getBytes().length));
			connection3.setRequestProperty("Content-Language", "en-US");
			

			
			connection3.setUseCaches(false);
			connection3.setDoInput(true);
			connection3.setDoOutput(true);
			System.out.println("Response code:"+connection3.getResponseCode());
			
			//List<String> cookies = connection3.getHeaderFields().get("Set-Cookie");
			//for(int i=0; i<cookies.size();i++)
			//	System.out.println("WAKAKA1:" + cookies.get(i));
			
			String headerName=null;
			String myCookieString = "";
			String cookie = "";
			List cookieList = new ArrayList<String>(); 
			
			for (int i=1; (headerName = connection3.getHeaderFieldKey(i))!=null; i++) {
				//System.out.println(headerName);
			 	if (headerName.equalsIgnoreCase("Set-Cookie")) {                  
			 		cookie = connection3.getHeaderField(i);
			 		
			 		String cookieArr1[] = cookie.split(",");
					for(int j=0; j<cookieArr1.length; j++){
						System.out.println("CCC:"+cookieArr1[j]);
						if(cookieArr1[j+1].startsWith(" ")){
							cookieList.add(cookieArr1[j] +","+ cookieArr1[j+1]);
							j++;
						}
						else{
							cookieList.add(cookieArr1[j]);	
						}
					}
			 	}
			}
			
			//connection3.addRequestProperty("Cookie", myCookieString);

			
			
			
			// Send request
			DataOutputStream wr3 = new DataOutputStream(connection3.getOutputStream());
			

			
			wr3.writeBytes(urlParameter3);
			wr3.flush();
			wr3.close();
			// Get Response
			InputStream is3 = connection3.getInputStream();
			BufferedReader rd3 = new BufferedReader(new InputStreamReader(is3, "utf-8"));
		    String line3;
		    String nexturl3="";
		    String pltn="";
		    while ((line3 = rd3.readLine()) != null) {
		    	//System.out.println(line3);
		    	if(line3.trim().length()==0){ // secure1 cannot use, then use secure2
		    		HttpURLConnection connection3a = null;
					//URL url3 = new URL("https://secure2.store.apple.com/hk-zh/sign_in?c=aHR0cDovL3N0b3JlLmFwcGxlLmNvbS9oay16aC9jYXJ0fDFhb3NjNTgxZWNjODBjNDQ2MWU5NThlNTBkNDA5ZDFhNWQzNzFkYmRkZTkx&o=O01GMzUz&r=SXYD4UDAPXU7P7KXF&s=aHR0cHM6Ly9zZWN1cmUyLnN0b3JlLmFwcGxlLmNvbS9oay16aC9jaGVja291dC9zdGFydD9wbHRuPTlDNjM0RjREfDFhb3NjMWIzYzE3ODVhYTc4ZmJmMzI2NzE4ZDVlNGNjOTIzNTA1YTAzY2U1&t=SXYD4UDAPXU7P7KXF&up=t");
					//URL url3 = new URL("https://secure2.store.apple.com/hk-zh/sentryx/sign_in");
		    		urlReferrer = "https://secure1.store.apple.com/hk-zh/sign_in?c="+c+"&o="+o+"&r="+r+"&s="+s+"&t="+t+"&up=t";
					URL url3a = new URL("https://secure1.store.apple.com/hk-zh/sentryx/sign_in?login-appleId=ccchungben@gmail.com&login-password=oyhoggnond3C&_a=login.sign&c="+c+"&_fid=si&r="+r+"&s="+s+"&t="+t+"&up=t");
					connection3a = (HttpURLConnection) url3a.openConnection();
					
					
					connection3a.setRequestMethod("POST");
					connection3a.setRequestProperty("Content-Type", "text/plain; charset=utf-8");
					connection3a.setRequestProperty("Content-Length",	"" + Integer.toString(urlParameter3.getBytes().length));
					connection3a.setRequestProperty("Content-Language", "en-US");
					connection3a.setUseCaches(false);
					connection3a.setDoInput(true);
					connection3a.setDoOutput(true);
					
					System.out.println("Response code:"+connection3.getResponseCode());
					
					for (int i=1; (headerName = connection3a.getHeaderFieldKey(i))!=null; i++) {
						if (headerName.equalsIgnoreCase("Set-Cookie")) {                  
					 		cookie = connection3a.getHeaderField(i);
					 		
					 		String cookieArr1[] = cookie.split(",");
							for(int j=0; j<cookieArr1.length; j++){
								System.out.println("CCC:"+cookieArr1[j]);
								if(cookieArr1[j+1].startsWith(" ")){
									cookieList.add(cookieArr1[j] +","+ cookieArr1[j+1]);
									j++;
								}
								else{
									cookieList.add(cookieArr1[j]);	
								}
							}
					 		
					 	}
					}
					
					
					//connection3a.addRequestProperty("Cookie", myCookieString);

					// Send request
					DataOutputStream wr3a = new DataOutputStream(connection3a.getOutputStream());
					
					wr3a.writeBytes(urlParameter3);
					wr3a.flush();
					wr3a.close();
					// Get Response
					InputStream is3a = connection3a.getInputStream();
					BufferedReader rd3a = new BufferedReader(new InputStreamReader(is3a, "utf-8"));
				    String line3a;
				    while ((line3a = rd3a.readLine()) != null) {
				    	//System.out.println(line3a);
				    	nexturl3 = line3a.substring(line3a.indexOf("\"url\"")+7,line3a.indexOf("\"}}}"));
				    	pltn = line3a.substring(line3a.indexOf("\"pltn\"")+8,line3a.indexOf("\"},\"method\""));
				    	break;
				    }
		    	}
		    	else{
		    		nexturl3 = line3.substring(line3.indexOf("\"url\"")+7,line3.indexOf("\"}}}"));
			    	pltn = line3.substring(line3.indexOf("\"pltn\"")+8,line3.indexOf("\"},\"method\""));
		    	}
	    	 break;
		    }
		   
		    //System.out.println("=================================================================");
	 		   System.out.println("333333333333333333333333333333333333333333333333333");
			   //System.out.println("=================================================================");
			    
			  
			   String urlParameter4 = "pltn="+pltn;
				HttpURLConnection connection4 = null;
				System.out.println(nexturl3+"?pltn="+pltn);
				URL url4 = new URL(nexturl3+"?pltn="+pltn);
				connection4 = (HttpURLConnection) url4.openConnection();
				
				//System.out.println("WAKAKA2:" + connection4.getHeaderField("Set-Cookie"));
				
				connection4.setRequestMethod("POST");
				connection4.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
				connection4.setRequestProperty("Content-Length",	"" + Integer.toString(urlParameter4.getBytes().length));
				connection4.setRequestProperty("Content-Language", "en-US");
				connection4.setRequestProperty("Referer", urlReferrer);
				connection4.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120 Safari/537.36");
				connection4.setRequestProperty("Cookie", "pxro=1; optimizelyEndUserId=oeu1398820677665r0.029224294004961848; optimizelyBuckets=%7B%7D; s_vnum_n2_en=1%7C1; dssid2=d9cb592d-2193-4317-89c2-47d8b410716d; dssf=1; optimizelySegments=%7B%22341793217%22%3A%22referral%22%2C%22341794206%22%3A%22false%22%2C%22341824156%22%3A%22gc%22%2C%22341932127%22%3A%22none%22%7D; optimizelyBuckets=%7B%7D; POD=us~en; s_invisit_n2_asia=8; s_vnum_n2_asia=8%7C1; s_vnum_n2_cn=3%7C1%2C0%7C2; s_vnum_n2_ca=0%7C2; s_vnum_n2_gb=0%7C3; dslang=GB-EN; ds01_a=e47036e114436cb3b5a95859ea28d8fce7c922fb6c3177f517edf6f5c86316569ecacbdc6c571c553435c522860352084ece84029c0a537e6f135b0b2e8bbd88b5b78a5878e10d7255688fee866c709afbe8b5bec0c9a8eaba3a0065ebe0413cGZVX; ccl=ocxdOPEFaZCyAIJivn+i/g==; geo=HK; s_vnum_n2_hk=17%7C1%2C5%7C2%2C3%7C18%2C12%7C4%2C0%7C15%2C13%7C3%2C4%7C4%2C26%7C2%2C21%7C2%2C38%7C1%2C70%7C1%2C97%7C1%2C71%7C1%2C20%7C8%2C30%7C2; s_vnum_n2_au=0%7C4%2C20%7C3; s_vnum_n2_jp=0%7C2%2C3%7C1%2C20%7C3; s_vnum_n2_us=4%7C33%2C17%7C1%2C3%7C22%2C12%7C1%2C10%7C1%2C0%7C14%2C13%7C1%2C19%7C19%2C98%7C1%2C25%7C1%2C97%7C1; asmetrics=%257B%2522store%2522%253A%257B%2522sid%2522%253A%2522wU94P7PKHH4CPTXU2%2522%257D%257D; sfa=hk-zh; asmetrics=%257B%2522store%2522%253A%257B%2522sid%2522%253A%2522wU94P7PKHH4CPTXU2%2522%257D%257D; s_cc=true; s_ppv=AOS%253A%2520Checkout%2520Sign%2520In%2C73%2C19%2C541%2C; s_fid=51FDEE4DE0FE74B1-199974F6E3D8CD13; s_sq=%5B%5BB%5D%5D; s_vi=[CS]v1|2938D8EF0514BEF2-40000175A010E2A5[CE]; ltn_hk-zh=1aosFlHTtGAjQvyuNAR9%2BFRt6lAR/68Do1f2th/LmS/mpi076FyQI4H%2BfXSkEU8YKPq%2BAUwDkuVtHBiz5mCblnbalWKx4kIl6qiOL/gzlFT9%2BBtrgeo0TMValCmygSwaQmGeB6CFjWwIKSVyIxhfOXupLUKyMfPZsTXvDJEK7w8L%2BXkoP/4GQmlJGi%2B8RYVal08NT%2BhfmXvbH3NsWVhCWATKcg%3D%3D; sltn_3dab7771_hk-zh=136ba7bab17789147242e7a99164279684dfa14d; recid=S4YFX2XK2YYJ9PFXHYHUHHC9X27Y774TKY9UH9J7HUXHY7DUA; disa=SJAKAUXJKD72HAJDTXDUK2FTJ9JCKXYY4JA7JAAXY27YTX7T4TUXDHUU794A7AFHPP7PXFA77YH744H949DPK7CAPJ2AJ7HX9XTKH494C9F94DD94FP2C44Y9P2DCDTJYDA9449XDUK7HYXDTJH7DFPYK4FH4AACH; aoscn=Q2hpIENodW5n~b121691f; dc=nc");
				
				//myCookieString = myCookieString.replace("domain=store.apple.com","domain=.store.apple.com");
				//System.out.println("myCookieString="+myCookieString);
				//connection4.addRequestProperty("Cookie", myCookieString);
				String finalCookie = "";
				for(int k=0; k<cookieList.size(); k++){
					//if( !((String)cookieList.get(k)).startsWith("recid") && !((String)cookieList.get(k)).startsWith("disa") && !((String)cookieList.get(k)).startsWith("aoscn")){
					//if( ((String)cookieList.get(k)).startsWith("ltn_hk-zh")){
					//if( ((String)cookieList.get(k)).startsWith("sltn_")){
						finalCookie += ((String)cookieList.get(k)).split("; version")[0] + "; ";
						//System.out.println("DDD:"+((String)cookieList.get(k)).split("; version")[0]);
						System.out.println("DDD:"+(String)cookieList.get(k));
						//System.out.println("DDD:"+((String)cookieList.get(k)).replace("; version=\"1\"",""));
						String tempCookie = (String)cookieList.get(k);
						tempCookie = tempCookie.replace("; version=\"1\"","");
						if(tempCookie.indexOf("domain=.")<0){
							tempCookie = tempCookie.replace("domain=", "domain=.");
						}
						System.out.println("EEE:"+tempCookie);
						//connection4.addRequestProperty("Cookie", tempCookie);
					//}
					
				}
				
				System.out.println("cookie="+finalCookie);
				connection4.setUseCaches(false);
				connection4.setDoInput(true);
				connection4.setDoOutput(true);
				
				System.out.println("Response code:"+connection4.getResponseCode());
				
				// Send request
				DataOutputStream wr4 = new DataOutputStream(connection4.getOutputStream());
				
				wr4.writeBytes(urlParameter4);
				wr4.flush();
				wr4.close();
				// Get Response
				InputStream is4 = connection4.getInputStream();
				BufferedReader rd4 = new BufferedReader(new InputStreamReader(is4, "utf-8"));
			    String line4;
			    //String nexturl3="";
			    //String pltn="";
			    while ((line4 = rd4.readLine()) != null) {
			    	System.out.println(line4);
			    	//output += line4;
			    }
		
			    
			    
			 
			    
			    
			    
			    
			    
		    
		} catch (Exception e) {
			e.printStackTrace();
		}
		return output;
	}
	
	public void addTask(){
		Config config = getConfig();
		String monitor = config.getMonitor();
		String refresh = config.getRefresh();
		
		
		if(monitor.equalsIgnoreCase("T")){
			Queue queue = QueueFactory.getDefaultQueue();
			if(refresh.equals("5")){
				queue.add(withUrl("/ipMon.jsp").countdownMillis(0));
				queue.add(withUrl("/ipMon.jsp").countdownMillis(5000));
				queue.add(withUrl("/ipMon.jsp").countdownMillis(10000));
				queue.add(withUrl("/ipMon.jsp").countdownMillis(15000));
				queue.add(withUrl("/ipMon.jsp").countdownMillis(20000));
				queue.add(withUrl("/ipMon.jsp").countdownMillis(25000));
				queue.add(withUrl("/ipMon.jsp").countdownMillis(30000));
				queue.add(withUrl("/ipMon.jsp").countdownMillis(35000));
				queue.add(withUrl("/ipMon.jsp").countdownMillis(40000));
				queue.add(withUrl("/ipMon.jsp").countdownMillis(45000));
				queue.add(withUrl("/ipMon.jsp").countdownMillis(50000));
				queue.add(withUrl("/ipMon.jsp").countdownMillis(55000));
			}
			else if(refresh.equals("10")){
				queue.add(withUrl("/ipMon.jsp").countdownMillis(0));
				queue.add(withUrl("/ipMon.jsp").countdownMillis(10000));
				queue.add(withUrl("/ipMon.jsp").countdownMillis(20000));
				queue.add(withUrl("/ipMon.jsp").countdownMillis(30000));
				queue.add(withUrl("/ipMon.jsp").countdownMillis(40000));
				queue.add(withUrl("/ipMon.jsp").countdownMillis(50000));
			}
			else if(refresh.equals("30")){
				queue.add(withUrl("/ipMon.jsp").countdownMillis(0));
				queue.add(withUrl("/ipMon.jsp").countdownMillis(30000));
			}
			else if(refresh.equals("60")){
				queue.add(withUrl("/ipMon.jsp").countdownMillis(0));
			}			
		}
	}
	
	public void sendMail(String subject, String body){
		  Config config = getConfig();
		  Properties props = new Properties();
	        Session session = Session.getDefaultInstance(props, null);

	        String msgBody = "http://store.apple.com/hk-zh/buy-iphone/iphone6<br/><br/>\r\n" + body;

	        try {
	        	
	        	if(!config.getReceiver().equals("-")){
	        		MimeMessage msg = new MimeMessage(session);
		            msg.setFrom(new InternetAddress(config.getSender()));
		            msg.addRecipient(Message.RecipientType.TO, new InternetAddress(config.getReceiver()));
		            msg.setSubject(subject);
		            msg.setText(msgBody, "utf-8", "html");
		            Transport.send(msg);
	        	}
	            
	           
	        	MimeMessage msg2 = new MimeMessage(session);
	            msg2.setFrom(new InternetAddress(config.getSender()));
	            //msg.addRecipient(Message.RecipientType.TO, new InternetAddress(config.getReceiver()));
	            msg2.addRecipient(Message.RecipientType.TO, new InternetAddress("admins"));
	            msg2.setSubject(subject);
	            msg2.setText(msgBody, "utf-8", "html");
	            Transport.send(msg2);
	            
	            

	        } catch (AddressException e) {
	        	e.printStackTrace();
	        } catch (MessagingException e) {
	        	e.printStackTrace();
			}
	}
	
	public void updateConfig(String monitor, String sender, String receiver, String smsFrom, String smsTo, String refresh, String device){
		ConfigDao configDao = new ConfigDao();
		Config config = new Config();
		config.setMonitor(monitor);
		config.setSender(sender);
		config.setReceiver(receiver);
		config.setSmsFrom(smsFrom);
		config.setSmsTo(smsTo);
		config.setRefresh(refresh);
		config.setDevice(device);
		configDao.updateConfig(config);
		
		MemcacheService syncCache = MemcacheServiceFactory.getMemcacheService();
		syncCache.setErrorHandler(ErrorHandlers.getConsistentLogAndContinue(Level.INFO));
		syncCache.clearAll();
		
		syncCache.put("monitor", monitor);
		syncCache.put("sender", sender);
		syncCache.put("receiver", receiver);
		syncCache.put("smsFrom", smsFrom);
		syncCache.put("smsTo", smsTo);
		syncCache.put("refresh", refresh);
		syncCache.put("device", device);
		
	}
	
	public Config getConfig(){
		MemcacheService syncCache = MemcacheServiceFactory.getMemcacheService();
		syncCache.setErrorHandler(ErrorHandlers.getConsistentLogAndContinue(Level.INFO));
		
		String monitor = (String) syncCache.get("monitor");
		String sender = (String) syncCache.get("sender");
		String receiver = (String) syncCache.get("receiver");
		String smsFrom = (String) syncCache.get("smsFrom");
		String smsTo = (String) syncCache.get("smsTo");
		String refresh = (String) syncCache.get("refresh");
		String device = (String) syncCache.get("device");
		
		Config config = new Config();
		
		if(monitor == null || sender == null || receiver == null || smsFrom == null || smsTo == null || refresh == null || device == null){
			ConfigDao configDao = new ConfigDao();
			config = configDao.getConfig();
			syncCache.put("monitor", config.getMonitor());
			syncCache.put("sender", config.getSender());
			syncCache.put("receiver", config.getReceiver());
			syncCache.put("smsFrom", config.getSmsFrom());
			syncCache.put("smsTo", config.getSmsTo());
			syncCache.put("refresh", config.getRefresh());
			syncCache.put("device", config.getDevice());
		}
		else{
			config.setMonitor(monitor);
			config.setSender(sender);
			config.setReceiver(receiver);
			config.setSmsFrom(smsFrom);
			config.setSmsTo(smsTo);
			config.setRefresh(refresh);
			config.setDevice(device);
		}
		return config;
		
	}
}
